//The MIT License
//
//Copyright (c) 2009 nodchip
//
//Permission is hereby granted, free of charge, to any person obtaining a copy
//of this software and associated documentation files (the "Software"), to deal
//in the Software without restriction, including without limitation the rights
//to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//copies of the Software, and to permit persons to whom the Software is
//furnished to do so, subject to the following conditions:
//
//The above copyright notice and this permission notice shall be included in
//all copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//THE SOFTWARE.
package tv.dyndns.kishibe.server;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

import tv.dyndns.kishibe.client.game.GameMode;
import tv.dyndns.kishibe.client.game.ProblemGenre;
import tv.dyndns.kishibe.client.game.ProblemType;
import tv.dyndns.kishibe.client.game.Transition;
import tv.dyndns.kishibe.client.packet.PacketRoomKey;

import com.google.inject.Inject;

public class GameManager {
	private final Game.Factory gameFactory;
	private final Random random = new Random();
	private final Map<Integer, Game> sessions = new ConcurrentHashMap<Integer, Game>();
	private final Map<PacketRoomKey, Game> matchingSessions = new HashMap<PacketRoomKey, Game>();
	private volatile List<PacketRoomKey> eventRooms = new ArrayList<PacketRoomKey>();
	private volatile Game gameWhole = null;

	@Inject
	public GameManager(Game.Factory gameFactory) {
		this.gameFactory = gameFactory;
	}

	// セッションを返す
	public Game getSession(int sessionId) {
		return sessions.get(sessionId);
	}

	// マッチング状態にあるセッションを返す
	public synchronized Game getMatchingSession(GameMode gameMode, String roomName, int classLevel,
			String theme, Set<ProblemGenre> genres, Set<ProblemType> types, boolean publicEvent,
			ServerStatusManager serverStatusManager, int userCode, String remoteAddress,
			BadUserManager badUserManager) {
		if (badUserManager.isLimitedUser(userCode, remoteAddress)) {
			badUserManager.addLimitedUser(userCode, remoteAddress);
			gameMode = GameMode.limited;
		}

		final PacketRoomKey roomKey = new PacketRoomKey(gameMode,
				gameMode == GameMode.theme ? theme : roomName, genres, types);

		Game result = null;
		if (!matchingSessions.containsKey(roomKey)
				|| matchingSessions.get(roomKey).getTransition() != Transition.Matching) {
			final boolean alone;
			final boolean event;

			switch (gameMode) {
			case vsCom:
				alone = true;
				event = false;
				break;
			case whole:
				alone = false;
				event = false;
				break;
			case event:
				alone = false;
				event = true;
				break;
			case theme:
				alone = false;
				event = false;
				break;
			case limited:
				alone = false;
				event = false;
				break;
			default:
				alone = false;
				event = false;
				break;
			}

			int sessionId;
			do {
				sessionId = random.nextInt(100000000);
			} while (sessions.containsKey(sessionId));

			Game game = gameFactory.create(sessionId, classLevel, event, alone, theme, publicEvent);
			matchingSessions.put(roomKey, game);
			sessions.put(sessionId, game);
			updateEventRooms();
			result = game;
		}

		if (result == null) {
			result = matchingSessions.get(roomKey);
		}

		if (gameMode == GameMode.whole) {
			gameWhole = result;
		}

		return result;
	}

	// 終了したセッションを消去する
	public void removeSession(int sessionId) {
		sessions.remove(sessionId);
		// System.out.println("ゲームセッション" + sessionId + "が削除されました - " + sessions.toString());
	}

	public void notifyMatchingCompleted() {
		updateEventRooms();
	}

	public List<PacketRoomKey> getEventRooms() {
		return eventRooms;
	}

	private synchronized void updateEventRooms() {
		final List<PacketRoomKey> eventRooms = new ArrayList<PacketRoomKey>();
		for (Entry<PacketRoomKey, Game> entry : matchingSessions.entrySet()) {
			final PacketRoomKey key = entry.getKey();
			final Game game = entry.getValue();
			if (game.isEvent() && game.isPublicEvent()
					&& game.getTransition() == Transition.Matching) {
				eventRooms.add(key);
			}
		}
		this.eventRooms = eventRooms;
	}

	public int getNumberOfPlayersInWhole() {
		final Game game = gameWhole;

		if (game == null || game.getTransition() != Transition.Matching) {
			return 0;
		} else {
			return game.getNumberOfHumanPlayer();
		}
	}

	public int getNumberOfSessions() {
		return sessions.size();
	}

	public int getNumberOfPlayers() {
		int numberOfPlayers = 0;
		for (Game game : sessions.values()) {
			numberOfPlayers += game.getNumberOfHumanPlayer();
		}
		return numberOfPlayers;
	}
}
